import type { IRole } from "@/api/role"
import { useRoleStore } from "@/stores/role"
// useRoleHelpers 其实就个hook
export const useRoleHelpers = ({
  pageSize,
  pageNum
}: {
  // Ref<number> 是ts  数据类型，在配置文件中处理过，会自动导入
  pageSize: Ref<number>
  pageNum: Ref<number>
}) => {
  const { proxy } = getCurrentInstance()!
  const editType = ref(-1)
  const visible = ref(false)
  const editData = ref<IRole | undefined>(undefined)
  const store = useRoleStore()
  // 抽屉组件的标题，添加还是修改
  const panelTitle = computed(() =>
    editType.value == 1 ? "增加角色" : "修改角色"
  )
  // 点击编辑弹窗
  const handleEditRole = (role: IRole) => {
    editType.value = 0
    editData.value = { ...role }
    visible.value = true
  }
  // 点击增加弹窗
  const hanleAddRole = () => {
    editType.value = 1
    editData.value = {} as IRole
    visible.value = true
  }
  // 添加角色
  const addNewRole = async (data: IRole) => {
    await store.addRole({
      ...data,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    proxy?.$message.success("角色添加成功")
    visible.value = false
  }
  // 编辑角色
  const editRow = async (data: IRole) => {
    await store.updateRole({
      ...data,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
    proxy?.$message.success("角色编辑成功")
    visible.value = false
  }
  // 表单提交
  const handleSubmit = async (data: IRole) => {
    // 增加
    if (editType.value === 1) {
      await addNewRole(data)
    } else {
      // 修改
      await editRow(data)
    }
  }
  // 删除角色
  const handleRemove = async (data: IRole) => {
    try {
      // 删除前，要确认
      await proxy?.$confirm("你确定删除" + data.name + "角色吗?", {
        type: "warning"
      })
      await store.removeRole({
        ...data,
        pageNum: pageNum.value,
        pageSize: pageSize.value
      })
      proxy?.$message.success("角色删除成功")
    } catch {
      proxy?.$message.info("取消删除")
    }
  }
  return {
    handleSubmit,
    handleRemove,
    handleEditRole,
    hanleAddRole,
    panelTitle,
    editType,
    visible,
    editData
  }
}
